package cn.lhy.tools;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;

import java.io.*;
import java.net.SocketException;

public class FTPUtils {
	private static Logger logger = Logger.getLogger(FTPUtils.class);
	/**
	 * 获取ftp客户端
	 * @return
	 */
	public static FTPClient getFTPClient() {
		String ftpIp = "127.0.0.1";
		String ftpAccount = "sxd";
		String ftpPassword = "sxd";
		String ftpPort = "21";
		FTPClient ftp = new FTPClient();
		try {
			ftp.connect(ftpIp, Integer.valueOf(ftpPort));
			ftp.login(ftpAccount, ftpPassword);
			int reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				throw new Exception("FTP连接失败，server: " + ftpIp + "，port: " + ftpPort);
			}
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ftp;
	}
	


	public static void deleteFile(String path, long time) {
		File file = new File(path);
		if (file.isDirectory()) {
			File[] files = file.listFiles();
			if (files == null || files.length == 0) {
				file.delete();
			} else {
				for (File f : files) {
					if (f.isDirectory()) {
						deleteFile(f.getPath(), time);
					}
					if (time != 0) {
						long lastModifyTime = f.lastModified();
						if (time - lastModifyTime <= 1000 * 3600) {
							continue;
						}
					}
					f.delete();
				}
			}
		}
	}

	public static void changeDirectory(String path, FTPClient ftpClient) {
		if ((path != null) && (path.charAt(0) != '/')) {
			path = "/" + path;
		}
		try {
			path = path.replace("\\", "/");
			if (!ftpClient.changeWorkingDirectory(path)) {
				String[] temp = null;
				if (path.lastIndexOf("\\") != -1) {
					temp = path.split("\\\\");
				} else {
					temp = path.split("/");
				}
				String tmpStr = "";
				for (int i = 1; i < temp.length; i++) {
					tmpStr = tmpStr + "/" + temp[i];
					if (!ftpClient.changeWorkingDirectory(new String(tmpStr.getBytes("GBK"), "iso-8859-1"))) {
						ftpClient.makeDirectory(new String(tmpStr.getBytes("GBK"), "iso-8859-1"));
					}
				}
				ftpClient.changeWorkingDirectory(new String(path.getBytes("GBK"), "iso-8859-1"));
			}
		} catch (Exception e) {
			System.out.println("改变ftp路径出错" + e.getStackTrace());
			throw new RuntimeException("改变ftp路径出错", e);
		}
	}

	/**
	 * 
	 * @param ftp
	 * @param filePath	ftp文件路径
	 * @param savePath	保存路径
	 * @return
	 */
	public static boolean downloadFile(FTPClient ftp, String filePath, String savePath) {
		filePath =filePath.replace("\\", "/");
		savePath =savePath.replace("/", "\\");
		File catalogFilePath = new File(savePath);
		if (!catalogFilePath.exists() && !catalogFilePath.isDirectory()) {// 如果文件夹不存在则创建
			logger.debug("文件目录不存在，创建。");
			catalogFilePath.mkdirs();
		}
		try {
			ftp.setFileType(2);
			ftp.setBufferSize(32768);
			// 判断是否连接成功
			int reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				logger.debug("FTP服务无法连接！");
				return false;
			}
			
			ftp.setRemoteVerificationEnabled(false);
			ftp.enterLocalPassiveMode();
			if (filePath.lastIndexOf("/") > 0) {
				String catalogPath = filePath.substring(0, filePath.lastIndexOf("/"));
				String fileName = filePath.substring((filePath.lastIndexOf("/") + 1));
				// 切换工作目录到文件所在的目录
				// boolean dir = ftp.changeWorkingDirectory(new
				// String(fileDir.getBytes(),FTP.DEFAULT_CONTROL_ENCODING));//如果是中文路径需要处理
				// 设置访问被动模式
				ftp.setRemoteVerificationEnabled(false);
				ftp.enterLocalActiveMode();
				boolean dir = ftp.changeWorkingDirectory(catalogPath);
				changeDirectory(catalogPath, ftp);
				if (dir) {
					// 检索ftp目录下所有的文件
					FTPFile[] fileList = ftp.listFiles();
					if (null != fileList && fileList.length > 0) {
						for (FTPFile file : fileList) {
							String ftpFileName = file.getName();
							if (ftpFileName.equals(fileName)) {
								File localFile = new File(savePath + File.separator + ftpFileName);
								OutputStream ios = new FileOutputStream(localFile);
								ftp.retrieveFile(ftpFileName, ios);
								ios.close();
							}
						}
					}
					return true;
				} else {
					logger.debug("服务器编码方式可能有问题，请检查！");
					return false;
				}
			} else {
				return false;
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.debug("ftp下载文件发生异常！");
			return false;
		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	/**
     * 上传文件
     * @param pathname ftp服务保存地址
     * @param fileName 上传到ftp的文件名
     *  @param originfilename 待上传文件的名称（绝对地址） * 
     * @return
     */
     public static boolean uploadFile(FTPClient ftp, String pathname, String fileName,String originfilename){
         boolean flag = false;
         InputStream inputStream = null;
         try{
             System.out.println("开始上传文件");
             inputStream = new FileInputStream(new File(originfilename));
             ftp.setFileType(ftp.BINARY_FILE_TYPE);
             CreateDirecroty(ftp,pathname);
            // ftp.makeDirectory(pathname);
             ftp.changeWorkingDirectory(pathname);
             ftp.storeFile(fileName, inputStream);
             inputStream.close();
             ftp.logout();
             flag = true;
             System.out.println("上传文件成功");
         }catch (Exception e) {
             System.out.println("上传文件失败");
             e.printStackTrace();
         }finally{
             if(ftp.isConnected()){ 
                 try{
                	 ftp.disconnect();
                 }catch(IOException e){
                     e.printStackTrace();
                 }
             } 
             if(null != inputStream){
                 try {
                     inputStream.close();
                 } catch (IOException e) {
                     e.printStackTrace();
                 } 
             } 
         }
         return true;
     }
     /**
      * 上传文件
      * @param pathname ftp服务保存地址
      * @param fileName 上传到ftp的文件名
      * @param inputStream 输入文件流 
      * @return
      */
     public static boolean uploadFile(FTPClient ftp, String pathname, String fileName,InputStream inputStream){
         boolean flag = false;
         try{
             System.out.println("开始上传文件");
             ftp.setFileType(ftp.BINARY_FILE_TYPE);
             CreateDirecroty(ftp,pathname);
             ftp.makeDirectory(pathname);
             ftp.changeWorkingDirectory(pathname);
             ftp.storeFile(fileName, inputStream);
             inputStream.close();
             ftp.logout();
             flag = true;
             System.out.println("上传文件成功");
         }catch (Exception e) {
             System.out.println("上传文件失败");
             e.printStackTrace();
         }finally{
             if(ftp.isConnected()){ 
                 try{
                	 ftp.disconnect();
                 }catch(IOException e){
                     e.printStackTrace();
                 }
             } 
             if(null != inputStream){
                 try {
                     inputStream.close();
                 } catch (IOException e) {
                     e.printStackTrace();
                 } 
             } 
         }
         return true;
     }


	/**
     * 改变目录路径
	 * @param ftp
     * @param directory
     * @return
     */
	public static boolean changeWorkingDirectory(FTPClient ftp,String directory) {
		 boolean flag = true;
		 try {
			 flag = ftp.changeWorkingDirectory(directory);
			 if (flag) {
			   System.out.println("进入文件夹" + directory + " 成功！");

			 } else {
				 System.out.println("进入文件夹" + directory + " 失败！开始创建文件夹");
			 }
		 } catch (IOException ioe) {
			 ioe.printStackTrace();
		 }
		 return flag;
	}

     //创建多层目录文件，如果有ftp服务器已存在该文件，则不创建，如果无，则创建
     public static boolean CreateDirecroty(FTPClient ftp,String remote) throws IOException {
         boolean success = true;
         String directory = remote + "/";
         // 如果远程目录不存在，则递归创建远程服务器目录
         if (!directory.equalsIgnoreCase("/") && !changeWorkingDirectory(ftp,new String(directory))) {
             int start = 0;
             int end = 0;
             if (directory.startsWith("/")) {
                 start = 1;
             } else {
                 start = 0;
             }
             end = directory.indexOf("/", start);
             String path = "";
             String paths = "";
             while (true) {
                 String subDirectory = new String(remote.substring(start, end).getBytes("GBK"), "iso-8859-1");
                 path = path + "/" + subDirectory;
                 if (!existFile(ftp,path)) {
                     if (makeDirectory(ftp,subDirectory)) {
                         changeWorkingDirectory(ftp,subDirectory);
                     } else {
                         System.out.println("创建目录[" + subDirectory + "]失败");
                         changeWorkingDirectory(ftp,subDirectory);
                     }
                 } else {
                     changeWorkingDirectory(ftp,subDirectory);
                 }

                 paths = paths + "/" + subDirectory;
                 start = end + 1;
                 end = directory.indexOf("/", start);
                 // 检查所有目录是否创建完毕
                 if (end <= start) {
                     break;
                 }
             }
         }
         return success;
     }

   //判断ftp服务器文件是否存在    
     public static boolean existFile(FTPClient ftp,String path) throws IOException {
             boolean flag = false;
             FTPFile[] ftpFileArr = ftp.listFiles(path);
             if (ftpFileArr.length > 0) {
                 flag = true;
             }
             return flag;
         }
     //创建目录
     public static boolean makeDirectory(FTPClient ftp,String dir) {
         boolean flag = true;
         try {
             flag = ftp.makeDirectory(dir);
             if (flag) {
                 System.out.println("创建文件夹" + dir + " 成功！");

             } else {
                 System.out.println("创建文件夹" + dir + " 失败！");
             }
         } catch (Exception e) {
             e.printStackTrace();
         }
         return flag;
     }
     
     /** * 下载文件 * 
     * @param pathname FTP服务器文件目录 * 
     * @param filename 文件名称 * 
     * @param localpath 下载后的文件路径 * 
     * @return */
     public static boolean downloadFile(FTPClient ftp,String pathname, String filename, String localpath){ 
         boolean flag = false; 
         OutputStream os=null;
         try { 
             System.out.println("开始下载文件");
             //切换FTP目录 
             ftp.changeWorkingDirectory(pathname); 
             FTPFile[] ftpFiles = ftp.listFiles(); 
             for(FTPFile file : ftpFiles){ 
                 if(filename.equalsIgnoreCase(file.getName())){ 
                     File localFile = new File(localpath + "/" + file.getName()); 
                     os = new FileOutputStream(localFile); 
                     ftp.retrieveFile(file.getName(), os); 
                     os.close(); 
                 } 
             } 
             ftp.logout(); 
             flag = true; 
             System.out.println("下载文件成功");
         } catch (Exception e) { 
             System.out.println("下载文件失败");
             e.printStackTrace(); 
         } finally{ 
             if(ftp.isConnected()){ 
                 try{
                	 ftp.disconnect();
                 }catch(IOException e){
                     e.printStackTrace();
                 }
             } 
             if(null != os){
                 try {
                     os.close();
                 } catch (IOException e) {
                     e.printStackTrace();
                 } 
             } 
         } 
         return flag; 
     }
     
     /** * 删除文件 * 
     * @param pathname FTP服务器保存目录 * 
     * @param filename 要删除的文件名称 * 
     * @return */ 
     public static boolean deleteFile(FTPClient ftp,String pathname, String filename){ 
         boolean flag = false; 
         try { 
             System.out.println("开始删除文件");
             //切换FTP目录 
             ftp.changeWorkingDirectory(pathname); 
             ftp.dele(filename); 
             ftp.logout();
             flag = true; 
             System.out.println("删除文件成功");
         } catch (Exception e) { 
             System.out.println("删除文件失败");
             e.printStackTrace(); 
         } finally {
             if(ftp.isConnected()){ 
                 try{
                	 ftp.disconnect();
                 }catch(IOException e){
                     e.printStackTrace();
                 }
             } 
         }
         return flag; 
     }
	
	public static void main(String[] args) {

//    	downloadFile(ftp, "/J10/20180413J1000013/1/6bb1b01584d84adcaccc34647ef67d88/SXD_20180413J1000013_1_000002.jpg", "C:\\ccc");
//    	uploadFile(ftp, "test2", "777.jpg", "C:\\Users\\sxd\\Desktop\\256020171006000189\\1\\SXD_256020171006000189_1_000000.jpg");
//    	try{
//    	Map<String, String> map = new HashMap<String, String>();
//    	map.put("F:/b/a", "\\12\\20180120183236.xls");
//    	map.put("F:/b/b", "\\11\\000003.jpg");
//    	map.put("F:/b/c", "\\10\\000001.jpg");
//		for (String key : map.keySet()) {
//			System.out.println("key= " + key + " and value= " + map.get(key));
//			downloadFile(ftp, map.get(key), key);
//		}
//    	}catch (Exception e) {
//    		
//    	} finally {
//			if (ftp != null)
//				try {
//					ftp.disconnect();
//				} catch (IOException ioe) {
//				}
//		}
    	
	}
}
